package io.gitee.luoyuan800.tool.llm.agent;

import io.gitee.luoyuan800.tool.llm.bean.AbstractMessage;
import io.gitee.luoyuan800.tool.llm.bean.completion.CommonChatCompletion;
import io.gitee.luoyuan800.tool.llm.bean.request.ChatRequest;
import io.gitee.luoyuan800.tool.llm.bean.request.QwenChatRequest;
import io.gitee.luoyuan800.tool.llm.bean.config.AiAgentConfig;
import io.gitee.luoyuan800.tool.llm.web.RestfulClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

@Slf4j
public class QwenAgent extends CommonAgent {
    private static final String URL = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";

    public QwenAgent(AiAgentConfig aiAgentConfig, RestfulClient restTemplate, String name) {
        super(aiAgentConfig, restTemplate, name);
        if (StringUtils.isBlank(aiAgentConfig.getUrl())) {
            aiAgentConfig.getModelConfig().setFullUrl(URL);
        }
    }

    @Override
    public CommonChatCompletion fullChat(String msg, int resultCount, String image, boolean enableThinking) {
        log.info("Sending message to {}({}).", getName(), getModel());
        log.debug("Message: {}", msg);

        QwenChatRequest request = buildRequest(resultCount);
        request.setStream(false);
        if(enableThinking!= request.getEnableThinking()){
            request.setEnableThinking(enableThinking);
        }
        List<AbstractMessage<?>> messageSend = addMessage(ChatRequest.MessageType.USER, msg, image);
        request.setMessages(messageSend);

        CommonChatCompletion response = httpRequest(request);

        tokenTrack(response);
        log.info("Got response from {}({}).", getName(), getModel());
        return response;
    }

    @Override
    QwenChatRequest buildRequest(int resultCount) {
        QwenChatRequest request = new QwenChatRequest();
        setRequestParams(resultCount, request);
        if (getAiAgentConfig().isWebSearch()) {
            request.setEnableSearch(true);
        }
        request.setEnableThinking(getAiAgentConfig().isEnableThink());
        request.setThinkingBudge(getAiAgentConfig().getThinkBudget());

        return request;
    }

}
